package com.sch.www.common.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;
import java.util.Date;

/**
 * 开始结束时间验证
 * Created by admin on 2017/2/18.
 */
public class EndTimeFluentValidator extends ValidatorHandler<Date> implements Validator<Date> {

    private Date startTime;
    private String fieldNameStartTime;
    private String fieldNameEndTime;
    private boolean power = true;

    public EndTimeFluentValidator(Date startTime, String fieldNameStartTime, String fieldNameEndTime) {
        this.fieldNameStartTime = fieldNameStartTime;
        this.fieldNameEndTime = fieldNameEndTime;
        this.startTime = startTime;
    }

    public EndTimeFluentValidator(Date startTime, String fieldNameStartTime, String fieldNameEndTime, boolean power) {
        this.fieldNameStartTime = fieldNameStartTime;
        this.fieldNameEndTime = fieldNameEndTime;
        this.startTime = startTime;
        this.power = power;
    }

    @Override
    public boolean validate(ValidatorContext context, Date endTime) {
        if ((startTime == null || endTime == null) && power == false) {
            return true;
        }


        if (null == endTime || startTime == null || endTime.getTime() < startTime.getTime()) {
            context.addError(ValidationError.create(String.format("%s必须大于%s", fieldNameEndTime, fieldNameStartTime))
                    .setErrorCode(-1)
                    .setField(fieldNameEndTime)
                    .setInvalidValue(endTime));
            return false;
        }
        return true;
    }

}
